package hcd.electrick;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by david on 2017/1/31.
 */
public class SelectDormFragment extends Fragment {

    private String session;

    private String[] list;
    private String[] floorList;
    private String[] dormList;

    private ListView buildListView;
    private ListView floorListView;
    private ListView dormListView;

    private BuildAdapter buildAdapter;
    private FloorAdapter floorAdapter;
    private DormAdapter dormAdapter;

    private int buildSelected = -1;
    private int floorSelected = -1;
    private int dormSelected = -1;

    private String buildID;
    private String floorID;
    private String dormID;

    private String buildName;
    private String dormName;

    private FloorListHandler floorListHandler;
    private DormListHandler dormListHandler;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getActivity().setTitle("选择宿舍");

        View rootView = inflater.inflate(R.layout.fragment_select_dorm, container, false);
        setHasOptionsMenu(true);
        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        list = getArguments().getStringArray("value");
        session = getArguments().getString("session");

        buildListView = (ListView) rootView.findViewById(R.id.build_listView);
        floorListView = (ListView) rootView.findViewById(R.id.floor_listView);
        dormListView = (ListView) rootView.findViewById(R.id.dorm_listView);

        buildAdapter = new BuildAdapter();
        buildListView.setAdapter(buildAdapter);
        buildListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        buildListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d("pos", String.valueOf(position));
                buildSelected = position;
                String[] info = list[position].split(",");
                if (info.length > 1){
                    buildID = info[0];
                    buildName = info[1];
                }
                buildAdapter.notifyDataSetInvalidated();
                getFloorList();

            }
        });

        floorAdapter = new FloorAdapter();
        floorListView.setAdapter(floorAdapter);
        floorListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        floorListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                floorSelected = position;
                String[] info = floorList[position].split(",");
                if (info.length > 1){
                    floorID = info[0];
                }
                floorAdapter.notifyDataSetInvalidated();
                getDormList();
            }
        });
        floorListHandler = new FloorListHandler();

        dormAdapter = new DormAdapter();
        dormListView.setAdapter(dormAdapter);
        dormListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        dormListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                dormSelected = position;
                String[] info = dormList[position].split(",");
                String[] floorInfo = floorList[floorSelected].split(",");
                if (info.length > 1 && floorInfo.length > 1){
                    dormID = info[0];
                    String[] nameAry = info[1].split("-");
                    if (nameAry.length > 1){
                        dormName = nameAry[1];
                        Log.d("dorm", buildName+dormName);
                        Log.d("dormID", buildID+", "+floorID+", "+dormID);
                        Log.d("dorm_raw", buildName+", "+floorInfo[1]+", "+info[1]);
                        SharedPreferences.Editor editor = getContext().getSharedPreferences("dorm", Context.MODE_PRIVATE).edit();
                        editor.putString("dorm_name", buildName+dormName);
                        editor.putString("build_id", buildID);
                        editor.putString("floor_id", floorID);
                        editor.putString("dorm_id", dormID);
                        editor.putString("buildNameRaw", buildName);
                        editor.putString("floorNameRaw", floorInfo[1]);
                        editor.putString("roomNameRaw", info[1]);
                        editor.commit();

                        getActivity().getSupportFragmentManager().popBackStack();
                    }
                }
                dormAdapter.notifyDataSetInvalidated();
            }
        });
        dormListHandler = new DormListHandler();


        return rootView;
    }


    private class BuildAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.length;
        }
        @Override
        public Object getItem(int position) {
            return list[position];
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getConvertView(list, buildSelected, convertView, position);
//            TextView title;
//            if (convertView == null){
//                convertView = LayoutInflater.from(getContext()).inflate(R.layout.listitem_dorm, null);
//                title = (TextView) convertView.findViewById(R.id.list_item_label);
//                convertView.setTag(title);
//            }else {
//                title = (TextView) convertView.getTag();
//            }
//
//            String buildName = "";
//            String[] buildInfo = list[position].split(",");
//            if (buildInfo.length > 1){
//                buildName = buildInfo[1];
//            }
//            title.setText(buildName);
//
//            if (position == buildSelected){
//                convertView.setBackgroundColor(Color.LTGRAY);
//            }else {
//                convertView.setBackgroundColor(Color.TRANSPARENT);
//            }
//            return convertView;
        }
    }

    private class FloorAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (floorList != null) return floorList.length;
            return 0;
        }
        @Override
        public Object getItem(int position) {
            if (floorList != null) return floorList[position];
            return null;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView title;
            if (convertView == null){
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.listitem_dorm, null);
                title = (TextView) convertView.findViewById(R.id.list_item_label);
                convertView.setTag(title);
            }else {
                title = (TextView) convertView.getTag();
            }

            String name = "";
            String[] info = floorList[position].split(",");
            if (info.length > 1){
                String[] nameAry = info[1].split("\\-");
                if (nameAry.length > 1){
                    name = nameAry[1];
                }

            }
            title.setText(name);

            if (position == floorSelected){
                convertView.setBackgroundColor(Color.LTGRAY);
            }else {
                convertView.setBackgroundColor(Color.TRANSPARENT);
            }
            return convertView;
//            return getConvertView(floorList, floorSelected, convertView, position);
        }
    }

    private class DormAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (dormList != null) return dormList.length;
            return 0;
        }
        @Override
        public Object getItem(int position) {
            if (dormList != null) return dormList[position];
            return null;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView title;
            if (convertView == null){
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.listitem_dorm, null);
                title = (TextView) convertView.findViewById(R.id.list_item_label);
                convertView.setTag(title);
            }else {
                title = (TextView) convertView.getTag();
            }

            String name = "";
            String[] info = dormList[position].split(",");
            if (info.length > 1){
                String[] nameAry = info[1].split("\\-");
                if (nameAry.length > 1){
                    name = nameAry[1];
                }

            }
            title.setText(name);

            if (position == dormSelected){
                convertView.setBackgroundColor(Color.LTGRAY);
            }else {
                convertView.setBackgroundColor(Color.TRANSPARENT);
            }
            return convertView;
//            return getConvertView(dormList, dormSelected, convertView, position);
        }
    }

    private View getConvertView(String[] data, int selected, View convertView, int position){
        TextView title;
        if (convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.listitem_dorm, null);
            title = (TextView) convertView.findViewById(R.id.list_item_label);
            convertView.setTag(title);
        }else {
            title = (TextView) convertView.getTag();
        }

        String name = "";
        String[] info = data[position].split(",");
        if (info.length > 1){
            name = info[1];
        }
        title.setText(name);

        if (position == selected){
            convertView.setBackgroundColor(Color.LTGRAY);
        }else {
            convertView.setBackgroundColor(Color.TRANSPARENT);
        }
        return convertView;
    }

    private void getFloorList(){
        dormListView.setVisibility(View.GONE);
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {

                    String postData = "building="+buildID;
                    String urlStr = getString(R.string.domain_name) + "/getRoom.php";
                    URL url = new URL(urlStr);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Cookie", session);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    PrintWriter pw = new PrintWriter(connection.getOutputStream());
                    pw.print(postData);
                    pw.flush();
                    connection.connect();
                    String result = "";
                    if (connection.getResponseCode() == 200){
                        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            result += line;
                        }
                        Log.d("result", result);
                        String[] data = result.split("\\|");
                        if (data.length > 1){
                            floorList = data;
                            floorListHandler.obtainMessage(0, data).sendToTarget();
                        }else {
                            Log.e("data", "illegal");
                        }
                        reader.close();
                    }else {
                        throw new Exception("网络错误");
                    }
                    pw.close();
                    connection.disconnect();
                }catch (Exception err) {
                    err.printStackTrace();
                }
            }
        }.start();
    }

    private void getDormList(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {

                    String[] info = floorList[floorSelected].split(",");
                    if (info.length < 2){
                        throw new Exception("list有问题");
                    }
                    String postData = "building="+buildID+"&floor="+info[0];
                    String urlStr = getString(R.string.domain_name) + "/getRoom.php";
                    URL url = new URL(urlStr);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Cookie", session);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    PrintWriter pw = new PrintWriter(connection.getOutputStream());
                    pw.print(postData);
                    pw.flush();
                    connection.connect();
                    String result = "";
                    if (connection.getResponseCode() == 200){
                        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            result += line;
                        }
                        Log.d("result", result);
                        String[] data = result.split("\\|");
                        if (data.length > 1){
                            dormList = data;
                            dormListHandler.obtainMessage(0, data).sendToTarget();
                        }else {
                            Log.e("data", "illegal");
                        }
                        reader.close();
                    }else {
                        throw new Exception("网络错误");
                    }
                    pw.close();
                    connection.disconnect();
                }catch (Exception err) {
                    err.printStackTrace();
                }
            }
        }.start();
    }

    @SuppressLint("HandlerLeak")
    private class FloorListHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            floorAdapter.notifyDataSetChanged();
            floorListView.setVisibility(View.VISIBLE);
        }
    }

    @SuppressLint("HandlerLeak")
    private class DormListHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dormAdapter.notifyDataSetChanged();
            dormListView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                getActivity().getSupportFragmentManager().popBackStack();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}
